﻿using AppSocketModel;
using AppSocketService.Account;
using AppSocketService.Vehicle;
using BCGPSCommon;
using BCGPSMongoData;
using MongoDB.Driver;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using System;

namespace AppSocketService.AlarmHistory
{
    public class AlarmNotifyHistoryService : ServiceBase, IAlarmNotifyHistoryService
    {
        private MongoDBCommand<AlarmNotifyHistoryDto> mongoCommand = new MongoDBCommand<AlarmNotifyHistoryDto>("AlarmNotifyHistory");
        private readonly AccountDto CurrentAccount;
        private readonly IVehicleService vehicleService;
        public AlarmNotifyHistoryService(IClaimsAccessor claimsAccesso, IAccountService accountService, IVehicleService vehicleService) : base(claimsAccesso)
        {
            CurrentAccount = accountService.GetCurrentAccount();
            this.vehicleService = vehicleService;
        }

        public Task SaveAsync(AlarmNotifyHistoryDto dto)
        {
            return mongoCommand.InsertDocumentAsync(dto);
        }

        #region 获取报警记录 企业
        public PageableList<AlarmNotifyHistoryDto> GetListCompany(DateTime ?start,DateTime ?end,string accountId, string imei, AlarmType? alarmType, AlarmNotifyType? notifyType, bool? isConfirm,bool isDelete, bool desc, int index, int size)
        {
            index = index > 0 ? index - 1 : 0; 

            List<string> wheres = new List<string>();

            if (claimsAccessor.AccountRole == AccountRole.SYSTEM)
            { 
                if (!string.IsNullOrWhiteSpace(accountId))
                {
                    wheres.Add($"AccountId:\"{accountId}\"");
                }
            }
            else
            {
                wheres.Add($"CompanyId:{CurrentAccount.CompanyId}");

                if (!string.IsNullOrWhiteSpace(accountId))
                {
                    wheres.Add($"AccountId:\"{accountId}\"");
                }
                else
                {
                    wheres.Add($"AccountId:\"{CurrentAccount.AccountId}\"");
                }
            }

            if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateDateTime:{$gte:ISODate('" + start.Value.ToString("yyyy-MM-ddTHH:mm:ss") + "'),$lte:ISODate('" + end.Value.ToString("yyyy-MM-ddTHH:mm:ss") + "')}");
            }
            else if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateDateTime:{$gte:ISODate('" + start.Value.ToString("yyyy-MM-ddTHH:mm:ss") + "')}");
            }
            if (end.HasValue && !start.HasValue)
            {
                wheres.Add("CreateDateTime:{$lte:ISODate('" + end.Value.ToString("yyyy-MM-ddTHH:mm:ss") + "')}");
            }


            if (!string.IsNullOrWhiteSpace(imei))
                wheres.Add($"IMEI:\"{imei}\"");

            if (alarmType.HasValue)
                wheres.Add($"AlarmType:\"{alarmType.GetDescriptionString()}\"");

            if (notifyType.HasValue)
                wheres.Add($"NotifyType:\"{notifyType.GetDescriptionString()}\"");

            if (isConfirm.HasValue)
                wheres.Add($"IsConfirm:{isConfirm.Value.ToString().ToLower()}");

            wheres.Add($"IsDelete:{isDelete.ToString().ToLower()}");

            string str = (wheres.Count > 0) ? "{" + string.Join(" , ", wheres) + "}" : "{Id:\"\"}";
         
            var list = mongoCommand.SelectDocumentsAsync(str,s=>s.CreateDateTime,desc,index,size).GetAwaiter().GetResult();

            Dictionary<string, string> dict = new Dictionary<string, string>();
            foreach (var item in list.Items)
            {
                if (dict.ContainsKey(item.IMEI))
                    item.VehicleNo = dict[item.IMEI];
                else
                {
                    item.VehicleNo = GetVehicleNo(item.IMEI);
                    dict.Add(item.IMEI, item.VehicleNo); 
                }
            }
            return list;
        }
        //获取车号
        private string  GetVehicleNo(string imei)
        {
            var dto = vehicleService.GetVehicleByImei(imei);
            if (dto == null)
                return "未绑定";
            else
                return dto.VehicleNo;

        }
        #endregion
         

        #region 报警确认
        public void AlarmConfirm(string id)
        {
            var update = Builders<AlarmNotifyHistoryDto>.Update
                .Set(s => s.ConfirmDatetime, BCGPSCommon.MongoDBDateTime.GetNowUtc())
                .Set(s => s.ConfirmAccountCode, CurrentAccount.AccountCode)
                .Set(s => s.IsConfirm, true);
            mongoCommand.UpdateDocumentAsync(s => s.Id == id, update).GetAwaiter().GetResult();
        }
        public void AlarmConfirm(List<string> list)
        {
            var update = Builders<AlarmNotifyHistoryDto>.Update
                .Set(s => s.ConfirmDatetime, BCGPSCommon.MongoDBDateTime.GetNowUtc())
                .Set(s => s.ConfirmAccountCode, CurrentAccount.AccountCode)
                .Set(s => s.IsConfirm, true);
            foreach (var item in list)
            {
                mongoCommand.UpdateDocumentAsync(s => s.Id == item, update).GetAwaiter().GetResult();
            } 
        }
        #endregion
    }
}
